package com.qupai.lib_base.utils.nds;

import android.util.Log;

import androidx.annotation.NonNull;

import com.alibaba.pdns.DNSResolver;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;

import okhttp3.Dns;

public class OkHttpDns implements Dns {

    public static boolean isLog = true;

    private static final String TAG = "OkHttpDns";

    private static OkHttpDns instance;
    private static Object lock = new Object();
    private DNSResolver mDNSResolver = DNSResolver.getInstance();

    private OkHttpDns() {
    }

    public static OkHttpDns getInstance() {
        if (null == instance) {
            synchronized (lock) {
                if (instance == null) {
                    instance = new OkHttpDns();
                }
            }
        }
        return instance;
    }

    @Override
    public List<InetAddress> lookup(@NonNull String hostname) throws UnknownHostException {
        //调用阿里云公共DNS Android SDK提供API进行域名解析
        String ip = mDNSResolver.getIPV4ByHost(hostname);
        if (isLog)
            Log.d(TAG, "mDnsCache IP: " + ip);

        if (ip != null) {
            //如果ip不为null，直接使用该ip进行网络请求
            return Arrays.asList(InetAddress.getAllByName(ip));
        }
        //如果返回null，走系统DNS服务解析域名
        return Dns.SYSTEM.lookup(hostname);
    }
}